﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kaskelot.Services.Model;

namespace Stockholm.SOA.Kaskelot.WCF.ServiceImplementation.Mapping
{
	public static class ValExtensions
	{
		public static DataContracts.Val ToContract(this Val entity)
		{
			DataContracts.Val b = new DataContracts.Val();

			CopyFromEntity(entity, b, false);

			return b;
		}

		public static DataContracts.Val ToMinimalContract(this Val entity)
		{
			DataContracts.Val b = new DataContracts.Val();

			CopyFromEntity(entity, b, true);

			return b;
		}

		public static Val ToEntity(this DataContracts.Val b)
		{
			Val entity = new Val();

			CopyToEntity(b, entity);

			return entity;
		}

		public static void Update(this Val entity, DataContracts.Val b)
		{
			CopyToEntity(b, entity);
		}

		private static void CopyFromEntity(Val from, DataContracts.Val to, bool minimal)
		{
			to.Id = from.Id;
			to.Namn = from.Benamning;

			to.Andrad = from.Andrad;
			to.AndradAv = from.AndradAv;
			to.Skapad = from.Skapad;
			to.SkapadAv = from.SkapadAv;

			to.Aktivt = from.Aktivt;
			to.ValDatum = from.ValDatum;
            to.DocumentLibraryId = from.DocumentLibraryId;

			if (minimal) return;
			if (from.Valkrets != null)
			{
				to.Valkretsar = new List<DataContracts.Valkrets>();
				foreach (Valkrets v in from.Valkrets)
				{
					to.Valkretsar.Add(v.ToMinimalContract());
				}
			}
		}

		private static void CopyToEntity(DataContracts.Val from, Val to)
		{
			to.Id = from.Id;
			to.Benamning = from.Namn;

			to.Andrad = from.Andrad;
			to.AndradAv = from.AndradAv;
			to.Skapad = from.Skapad;
			to.SkapadAv = from.SkapadAv;

			to.Aktivt = from.Aktivt;
			to.ValDatum = from.ValDatum;
            to.DocumentLibraryId = from.DocumentLibraryId;
		}
	}
}
